package com.chatplus.application.controller.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.common.page.PageParam;
import com.chatplus.application.domain.entity.orders.OrderEntity;
import com.chatplus.application.domain.request.PlusPageRequest;
import com.chatplus.application.domain.response.OrderDetailApiResponse;
import com.chatplus.application.domain.response.PlusPageResponse;
import com.chatplus.application.service.orders.OrderService;
import com.chatplus.application.web.basecontroller.BaseController;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

/**
 * 订单API
 */
@Validated
@RestController
@RequestMapping("/api/order")
@Tag(name = "订单API", description = "订单API")
public class OrderApiController extends BaseController {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(OrderApiController.class);
    private final OrderService orderService;
    public OrderApiController(OrderService orderService) {
        this.orderService = orderService;
    }
    @PostMapping("/list")
    @Operation(summary = "获取用户订单列表")
    public PlusPageResponse<OrderDetailApiResponse> list(@RequestBody PlusPageRequest plusPageRequest) {
        PageParam pageParam = new PageParam(plusPageRequest.getPage(), plusPageRequest.getPageSize());
        Page<OrderEntity> pageDTO = orderService.page(pageParam.toPage(), Wrappers.<OrderEntity>lambdaQuery()
                .eq(OrderEntity::getUserId, getUserId())
                .orderByDesc(OrderEntity::getCreatedAt));
        List<OrderEntity> orderEntityList = pageDTO.getRecords();
        if (CollUtil.isEmpty(orderEntityList)) {
            return new PlusPageResponse<>(plusPageRequest.getPage(), 0, 0, 0, Lists.newArrayList());
        }
        List<OrderDetailApiResponse> responseList = orderEntityList.stream().map(OrderDetailApiResponse::build).toList();
        return new PlusPageResponse<>(pageParam.getCurrent(), pageParam.getSize()
                , pageDTO.getPages(), pageDTO.getTotal(), responseList);
    }
}
